/* eslint-disable react-hooks/exhaustive-deps */
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import * as Yup from 'yup';

// yarn add formik,
//formik 表单数据绑定库
import { useFormik } from 'formik';
import { useDispatch } from 'react-redux';
import { loginAction, sendCodeAction } from '@/store/action/login';
import { useEffect, useRef, useState } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { Toast } from 'antd-mobile';
import { LocationStateType } from '@/components/AuthRoute';

export default function Login(props: any) {
  let history = useHistory();
  let location = useLocation<LocationStateType>();
  const formik = useFormik({
    // 初始化
    initialValues: {
      mobile: '16666677777',
      code: '',
    },
    // onSubmit必传属性
    // 登录
    onSubmit: async (values) => {
      // console.log(values);
      try {
        await dispatch(loginAction(values));
      } catch (error: any) {
        console.dir(error);
        if (error.response.status === 400) {
          Toast.show({ content: error.response.data.message });
        }
        return;
      }
      // 跳转页面
      // { from = '/' }解构时设置默认值
      const { from = '/' } = location.state || {};
      history.push(from);
      // history.push('/');

      Toast.show({ content: '登录成功' });
    },

    // // 🔑 validate函数，接收更新的values，返回错误信息组成的对象
    // // 用来校验表单
    // validate: (values) => {
    //   // console.log(values);
    //   let errors = {} as typeof values;
    //   if (!/^1[3-9]\d{9}$/.test(values.mobile)) {
    //     errors.mobile = '手机号格式错误';
    //   }
    //   if (!/^\d{6}$/.test(values.code)) {
    //     errors.code = '验证码格式错误';
    //   }
    //   // 返回错误信息组成的对象;
    //   return errors;
    // },

    // formik库表单校验 validate属性和validationSchema属性二选一
    // 用Yup表单校验库,校验表单
    // https://www.npmjs.com/package/yup
    validationSchema: Yup.object().shape({
      // 校验不通过会返回错误信息
      mobile: Yup.string()
        // required必传的
        .required('手机号不能为空!')
        // matches匹配项,接收两个参数
        .matches(/^1[3-9]\d{9}$/, '手机号格式错误'),

      code: Yup.string()
        .required('验证码不能为空!')
        .matches(/^\d{6}$/, '验证码格式错误'),
    }),
  });
  const [second, setSecond] = useState(0);
  const dispatch = useDispatch();

  const timerIdRef = useRef(0);
  // 组件卸载时清除定时器
  useEffect(() => {
    return () => {
      clearInterval(timerIdRef.current);
    };
  }, []);

  // 发送验证码
  const handleSendCode = () => {
    // console.log(formik.errors);

    if (formik.errors.mobile) return;
    dispatch(sendCodeAction(formik.values.mobile));

    setSecond(60);

    // 要修改成window.setInterval,需要的类型是number,默认是NodeJs的setInterval
    timerIdRef.current = window.setInterval(() => {
      // console.log('定时器运行');
      // setSecond是异步的方法,拿不到上面修改后的新值,需要第二种写法setSecond((修改后的旧值)=>新值)
      setSecond((oldSecond) => {
        // console.log(oldSecond);
        if (oldSecond === 1) {
          clearInterval(timerIdRef.current);
        }
        return oldSecond - 1;
      });
    }, 1000);
  };

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.push('/')}>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          {/* 手机号输入框 */}
          <Input
            autoFocus
            placeholder="请输入手机号"
            autoComplete="off"
            type="text"
            name="mobile"
            maxLength={11}
            // 错误信息
            errorMsg={formik.touched.mobile ? formik.errors.mobile : ''}
            value={formik.values.mobile}
            onChange={formik.handleChange}
            // 修改校验时机-为失去焦点时校验
            // 🔑 移动端，formik.touched表示是否触摸过该字段
            // 💥 touched需要和onBlur配合使用
            // 步骤：
            onBlur={formik.handleBlur}
          />

          {/* 短信验证码输入框 */}
          <Input
            placeholder="请输入验证码"
            autoComplete="off"
            type="text"
            name="code"
            maxLength={6}
            errorMsg={formik.touched.code ? formik.errors.code : ''}
            extra={
              second === 0 ? (
                <span onClick={handleSendCode}>获取验证码</span>
              ) : (
                <span>{second}秒后获取</span>
              )
            }
            value={formik.values.code}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />

          {/* 登录按钮 */}
          <button
            type="submit"
            className="login-btn"
            // formik.isValid表示表单校验是否通过
            disabled={!formik.isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  );
}
